var $ = require('jquery');
var util = require('imutil');
var Backbone = require('backbone');
var tpl = require('../tpl');

var Users = require('../model/users');

var SearchView = require('./search');
var ContactsListView = require('./users');
var bus = require('bus');


module.exports = Backbone.View.extend({
	el: null,
	template: tpl.contacts.wrap,
	initialize: function(options, api){
		this.api = api;
		
		this.render();
		this.views = {};

		this.contacts = new Users(this.api.models.contacts.toJSON());
		
		this.views.search = new SearchView({
			el: this.$('.J-im-contacts-search'),
			collection: this.contacts
		}, this.api);
		
		this.views.contacts = new ContactsListView({
			el: this.$('.J-im-contacts-list'),
			collection: this.contacts
		}, this.api);

        this.listenTo(this.api.models.contacts, 'reset change:unread add remove', function(){
            this.contacts.reset(this.api.models.contacts.toJSON());
        });

        this.listenTo(bus, 'searchInputFocus', function(msg){
            this.searchStart();
        });
        
        /*
        this.listenTo(bus, 'receiveMessage', function(msg){
            this.contacts.reset(this.api.models.contacts.toJSON());
        });*/

        this.listenTo(bus,'searchContacts cleanSearchWord',function(keyword,el){
            this._search(keyword);
        });
        this.listenTo(bus,'cancelSearch',function(keyword,el){
            this.cancelSearch();
        });


	},
	render: function(){
		this.$el.append(this.template());
	},
    _search: function(val){
        var keyword = val || $(".J-im-keywords").val();
        if(keyword=="" && this.views.contacts.isSearchResult){
            this.contacts.reset(null);
        }else{
            keyword = keyword.toLowerCase();
            var searchData = this.api.models.contacts.toJSON().filter(function(c){
                return (c.name.toLowerCase().indexOf(keyword)>-1|| c.comname.toLowerCase().indexOf(keyword)>-1||c.userNickName.toLowerCase().indexOf(keyword)>-1)
            });
            this.contacts.reset(searchData);
        }
    },
    cancelSearch:function(){
        this.views.search.blur();
        this.views.contacts.isSearchResult = false;
        this._search();
    },
    searchStart:function(){
        this.views.contacts.isSearchResult = true;
        var keyword = $(".J-im-keywords").val();
        if(keyword==""){
            this.contacts.reset(null);
        }
    }
});